package org.abratuhi.kvngroupware.model;

import java.util.ArrayList;
import java.util.Date;

import org.abratuhi.kvngroupware.gui.GUIScenarioManager;
import org.jdom.Element;

public class Scenario {
	
	String id = new String();
	String name = new String();
	String teamId = new String();
	ArrayList<String> jokeIds = new ArrayList<String>();
	
	GUIScenarioManager gui;
	
	public Scenario(){
		setId();
	}
	
	public Scenario(String teamId, String name){
		setTeamId(teamId);
		setName(name);
		setId();
	}
	
	void setId(){
		this.id = teamId + String.valueOf(new Date().getTime());
	}
	void setId(String id){
		this.id = id;
	}
	void setTeamId(String teamId){
		this.teamId = teamId;
	}
	void setName(String name){
		this.name = name;
	}
	public void setGUI(GUIScenarioManager gui){
		this.gui = gui;
	}
	
	public String getId(){
		return this.id;
	}
	public String getTeamId(){
		return this.teamId;
	}
	public String getName(){
		return this.name;
	}
	public GUIScenarioManager getGUI(){
		return this.gui;
	}
	
	public void add(String jokeId){
		this.jokeIds.add(jokeId);
	}
	public boolean contains(String jokeId){
		return this.jokeIds.contains(jokeId);
	}
	public int indexOf(String jokeId){
		return this.jokeIds.indexOf(jokeId);
	}
	public String get(int index){
		return this.jokeIds.get(index);
	}
	public void remove(String jokeId){
		this.jokeIds.remove(jokeId);
	}
	public int size(){
		return this.jokeIds.size();
	}
	public void exchange(int index1, int index2){
		String jokeId2 = get(index2);
		this.jokeIds.set(index2, get(index1));
		this.jokeIds.set(index1, jokeId2);
	}
	public void up(String jokeId){
		int index2 = indexOf(jokeId);
		int index1 = index2>0? index2-1 : index2;
		exchange(index1, index2);
	}
	public void down(String jokeId){
		int index1 = indexOf(jokeId);
		int index2 = index1<size()-1? index1+1 : index1;
		exchange(index1, index2);
	}
	
	public static Scenario fromElement(Element eScenario){
		System.out.println("scenario from element: "+eScenario.getAttributeValue("id"));
		Scenario scenario = new Scenario();
		scenario.setId(eScenario.getAttributeValue("id"));
		scenario.setName(eScenario.getAttributeValue("name"));
		scenario.setTeamId(eScenario.getAttributeValue("teamId"));
		for(int i=0; i<eScenario.getChildren("joke").size(); i++){
			scenario.add(((Element) eScenario.getChildren("joke").get(i)).getAttributeValue("id"));
		}
		return scenario;
	}
	
	public Element toElement(){
		Element eScenario = new Element("scenario");
		eScenario.setAttribute("id", getId());
		eScenario.setAttribute("name", getName());
		eScenario.setAttribute("teamId", getTeamId());
		for(int i=0; i<jokeIds.size(); i++){
			Element eJoke = new Element("joke");
			eJoke.setAttribute("id", jokeIds.get(i));
			eScenario.addContent(eJoke);
		}
		return eScenario;
	}

}
